/**
 * @Auther: ayo
 * @Date: 2018/8/22 16:59
 * @Description: // 封装的http方法
 */
import { Injectable } from '@angular/core';
import { LoadingProvider } from './loadingUtil';
import { NetworkConfig } from '../../app.networkConfig';
import { HttpClient } from '@angular/common/http';
import { ToastProvider } from './toastUtil';
import { Utils } from './utils';
import { catchError, map } from 'rxjs/internal/operators';

@Injectable()
export class HttpProvider {

    constructor(private httpClient: HttpClient, private _loadingProvider: LoadingProvider, private toastProvider: ToastProvider) {
    }

    /**
     * 处理http错误
     */
    handleHttpError(resp): any {
        setTimeout(() => {
            this._loadingProvider.dismiss();
        });
        console.log(resp);
        let errMsg = '抱歉，后台服务出错了';
        if (resp) {
            const msg: string = resp.message;
            if (msg && msg.toLowerCase().indexOf('timeout') > -1) {
                errMsg = '请求超时，请稍后重试！';
            } else {
                switch (resp.status) {
                    case 401:
                        errMsg = '无权限访问，或许登录信息已过期，请重新登录';
                        break;
                    case 404:
                        errMsg = '抱歉，后台服务找不到对应接口';
                        break;
                    case 0:
                        errMsg = '网络无法连接';
                        break;
                    default:
                        break;
                }
            }
        }
        this.toastProvider.toast(errMsg);
        // 统一返回格式
        return {success: false, msg: errMsg, result: null};
    }

    /**
     * get方法
     * @param url 请求url
     * @param options 请求选项
     * @param success 请求选项
     * @param loadingFlag 是否显示loading条，目前提供给packageDetail使用
     * @param error 失败回调
     */
    get(url: string, options: any = NetworkConfig.ENV.headers, success: Function, loadingFlag?: boolean, error?: Function) {
        url = encodeURI(url);
        if (Utils.isEmpty(loadingFlag) || true === loadingFlag) {
            this._loadingProvider.loading('open', '加载中...');
        }
        return this.httpClient.get(url, options).pipe(map(resp => {
                setTimeout(() => {
                    this._loadingProvider.dismiss();
                });
                if ('0' === resp['status']) {
                    success(resp);
                } else {
                    if (error) {
                        error(resp);
                    } else {
                        this.toastProvider.toast(resp['msg']);
                    }
                }
            }),
            catchError(resp => this.handleHttpError(resp)));
    }

    /**
     * post方法
     * @param url 请求url
     * @param param 请求参数
     * @param options 请求选项
     * @param success 成功回调
     * @param loadingFlag 是否显示loading条
     * @param error 失败回调
     */
    post(url: string, param: any = {}, options: any = NetworkConfig.ENV.headers, success: Function, loadingFlag?: boolean,
         error?: Function) {
        url = encodeURI(url);
        this._loadingProvider.loading('open', '加载中...');
        return this.httpClient.post(url, param, options).pipe(map(resp => {
                setTimeout(() => {
                    this._loadingProvider.dismiss();
                });
                if ('0' === resp['status']) {
                    success(resp);
                } else {
                    if (error) {
                        error(resp);
                    } else {
                        this.toastProvider.toast(resp['msg']);
                    }
                }
            }),
            catchError(resp => this.handleHttpError(resp)));
    }

    /**
     * put方法
     * @param url 请求url
     * @param param 请求参数
     * @param options 请求选项
     * @param success 成功回调
     * @param loadingFlag 是否显示loading条
     * @param error 失败回调
     */
    put(url: string, param: any = {}, options: any = NetworkConfig.ENV.headers, success: Function, loadingFlag?: boolean,
        error?: Function) {
        url = encodeURI(url);
        this._loadingProvider.loading('open', '加载中...');
        return this.httpClient.put(url, param, options).pipe(map(resp => {
                setTimeout(() => {
                    this._loadingProvider.dismiss();
                });
                if ('0' === resp['status']) {
                    success(resp);
                } else {
                    if (error) {
                        error(resp);
                    } else {
                        this.toastProvider.toast(resp['msg']);
                    }
                }
            }),
            catchError(resp => this.handleHttpError(resp)));
    }

    /**
     * delete方法
     * @param url 请求url
     * @param options 请求选项
     * @param success 成功回调
     * @param loadingFlag 是否显示loading条
     * @param error 失败回调
     */
    delete(url: string, options: any = NetworkConfig.ENV.headers, success: Function, loadingFlag?: boolean, error?: Function) {
        url = encodeURI(url);
        this._loadingProvider.loading('open', '加载中...');
        return this.httpClient.delete(url, options).pipe(map(resp => {
                setTimeout(() => {
                    this._loadingProvider.dismiss();
                });
                if ('0' === resp['status']) {
                    success(resp);
                } else {
                    if (error) {
                        error(resp);
                    } else {
                        this.toastProvider.toast(resp['msg']);
                    }
                }
            }),
            catchError(resp => this.handleHttpError(resp)));
    }
}

// 处理过的响应数据
// export interface IResponseData<T> {
//     success: boolean;
//     msg: string;
//     // 响应数据
//     result?: T;
// }
